package com.ruoyi.common.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {
    //交换机名称
    public static final String IPAY_TEST_EXCHANGE = "ipay_test_exchange";
    //队列名称
    public static final String IPAY_QUEUE = "ipay_queue";


    // 死信的交换机名
    final String DEAD_LETTER_EXCHANGE="ipay_dead_exchange";
    final String DEAD_LETTER_EXCHANGE_KEY="ipay_dead_exchange_key";
    final String DEAD_LETTER_ROUNTING_KEY="ipay_dead_rounting_key";

    @Bean
    public Queue maintainQueue() {
        Map<String,Object> args=new HashMap<>();
        // 设置该Queue的死信的信箱
        args.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE);
        // 设置死信routingKey
        args.put("x-dead-letter-routing-key", DEAD_LETTER_EXCHANGE_KEY);
        return new Queue(DEAD_LETTER_ROUNTING_KEY,true,false,false,args);
    }

    @Bean
    public Binding maintainBinding() {
        return BindingBuilder.bind(maintainQueue()).to(DirectExchange.DEFAULT)
                .with(DEAD_LETTER_ROUNTING_KEY);
    }

    @Bean
    public Queue deadLetterQueue(){
        return new Queue(DEAD_LETTER_EXCHANGE_KEY);
    }

    @Bean
    public DirectExchange deadLetterExchange() {
        return new DirectExchange(DEAD_LETTER_EXCHANGE, true, false);
    }

    @Bean
    public Binding deadLetterBindding(){
        return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange()).with(DEAD_LETTER_EXCHANGE_KEY);
    }


    //声明交换机
    @Bean("ipayTestExchange")
    public Exchange topicExchange(){
        return ExchangeBuilder.topicExchange(IPAY_TEST_EXCHANGE).durable(true).build();
    }

    //声明队列
    @Bean("ipayQueue")
    public Queue itemQueue(){
        return QueueBuilder.durable(IPAY_QUEUE).build();
    }

    //绑定队列和交换机
    @Bean
    public Binding itemQueueExchange(@Qualifier("ipayQueue") Queue queue,
                                     @Qualifier("ipayTestExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("ipay.#").noargs();
    }

}
